<template>
  <q-dialog v-model="dialog" position="bottom">
    <div class="bg-white full-width" style="border-radius: 8px 8px 0px 0px">
      <div>
        <img @click="close" style="width: 16px;height: 16px;" src="~/assets/images/public/close.png" alt="">
        <!-- <q-btn padding="sm sm" @click="close" style="color: #999" unelevated round icon="close" /> -->
      </div>

      <section class="q-px-md q-pb-md q-pt-sm">
        <div class="q-mb-sm" style="color: #666">请在方框内签字</div>
        <div class="canvas-box" style="height: 200px">
          <canvas ref="SignatureRef" class="full-width full-height"></canvas>
        </div>

        <div class="flex items-center justify-between q-mt-md">
          <div class="flex-1 q-mr-md" style="width: 80px">
            <q-btn
              color="secondary"
              @click="clear"
              class="full-width"
              outline
              unelevated
              rounded
              label="清空"
            />
          </div>
          <div class="flex-1" style="width: 80px">
            <q-btn
              class="full-width"
              style="background-color: #096AFF; color: #fff; font-size: 15px; font-weight: 600"
              unelevated
              :loading="loading"
              @click="submit"
              rounded
              label="确认"
            />
          </div>
        </div>
      </section>
    </div>
  </q-dialog>
</template>

<script setup lang="ts">
import { pngBase64ToFile } from 'src/utils/fileUtil';
import { showLoadingToast, showToast } from 'vant';
import { onMounted } from 'vue';
import { ref, watchEffect } from 'vue';
import SignaturePad from 'signature_pad';
import { computed } from 'vue';
import { Show } from './SignatureDialog';
import { Param } from './Protocol';
import { getConfigInfoApi } from 'src/api/oss';
import OSS from 'ali-oss';
import { v4 as uuidv4 } from 'uuid';
import { approveToPushApi } from 'src/api/info';
import { useAppStore } from 'src/stores/app-store';
import { useRoute, useRouter } from 'vue-router';
import { useAfterHandler } from './afterHandler';


const router = useRouter()
const route = useRoute()
const dialog = ref(false);
const loading = ref(false)
const SignatureRef = ref<HTMLCanvasElement>();

function createHDCanvas(canvas: HTMLCanvasElement) {
  const ratio = window.devicePixelRatio || 2;
  const { width, height } = canvas.getBoundingClientRect();
  canvas.width = width * ratio; // 实际渲染像素
  canvas.height = height * ratio; // 实际渲染像素
  const ctx = canvas.getContext('2d');
  if (!ctx) return;
  ctx.scale(ratio, ratio);
  // canvas 绘制
  return canvas;
}

const signaturePadInstantiate = ref<SignaturePad>();
watchEffect(() => {
  if (!SignatureRef.value) return;
  createHDCanvas(SignatureRef.value);
  signaturePadInstantiate.value?.clear();
  signaturePadInstantiate.value = new SignaturePad(SignatureRef.value);
});

const param = ref<Param>();

const show: Show = (_param) => {
  param.value = _param;
  dialog.value = true;
};
const close = () => {
  dialog.value = false;
};

const clear = () => {
  signaturePadInstantiate.value?.clear();
};

const submitPost = async (image: string) => {
  if (!param.value) return;
  const res = await getConfigInfoApi({ bizType: 'APPROVE' });
  const { accessKeyId, accessKeySecret, securityToken, endpoint, bucketName, path, hostUrl } = res.data;
  const ossClient = new OSS({
    // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
    accessKeyId,
    accessKeySecret,
    // 从STS服务获取的安全令牌（SecurityToken）。
    stsToken: securityToken,
    refreshSTSToken: async () => {
      // 向您搭建的STS服务获取临时访问凭证。
      const res = await getConfigInfoApi({ bizType: 'APPROVE' });
      const { accessKeyId, accessKeySecret, securityToken } = res.data;
      return {
        accessKeyId,
        accessKeySecret,
        stsToken: securityToken,
      };
    },
    // 填写Bucket名称。
    endpoint,
    bucket: bucketName,
  });
  const newUuid = uuidv4();
  const approvePathTemp = path.startsWith('/') ? path.slice(1, path.length) : path;
  const approvePath = approvePathTemp.endsWith('/')
    ? approvePathTemp.slice(0, approvePathTemp.length - 1)
    : approvePathTemp;
  const fileKey = `${approvePath}/${newUuid}.png`;
  const filePath = `${approvePath}/${param.value.orderId}/${newUuid}.png`;
  const file = pngBase64ToFile(image, `${newUuid}.png`);
  await ossClient.put(fileKey, file)
  const approveImageUrl = `${hostUrl.endsWith('/') ? hostUrl.slice(0, hostUrl.length - 1) : hostUrl}/${filePath}`

  await approveToPushApi({
    orderId: param.value.orderId,
    itemOrderIds: param.value.itemOrderIds,
    approveImageUrl
  })

};
const submit = async () => {
  if (!signaturePadInstantiate.value) return;
  if (signaturePadInstantiate.value.isEmpty()) {
    return showToast('请在方框内签字');
  }
  const image = signaturePadInstantiate.value.toDataURL('image/png');

  loading.value = true
  const toast = showLoadingToast({
    iconSize: 50,
    forbidClick: true,
    duration: 0,
  });
  await submitPost(image).finally(() => loading.value = false)
  toast.close()

  useAfterHandler(router, route).afterHandler()
};

defineExpose({ show });
</script>

<style scoped lang="scss">
.canvas-box {
  border: 1px solid rgba($color: grey, $alpha: 0.5);
  border-radius: 8px;
  overflow: hidden;
}
</style>
